/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.obrock;

import android.content.Context;
import android.database.Cursor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Дмитрий Г. Кузнецов
 */
public class Analytics implements Serializable {

    //public static final int TYPE_NORMAL = 0;
    //public static final int TYPE_PROGNOSIS = 1;

    public long analyticsID = -1L;
    public long parentID = -1L;
    public String name = "";
    public String remark = "";
    public double balance = 0.0;
    public double balanceDebt = 0.0;
    public double balanceCredit = 0.0;
    public Account account = null;
    public boolean selected = false;
    public Analytics[] values = new Analytics[]{};

    private static Database db;

    public Analytics(Database db, Account ref, long id) {
        this(db);
        analyticsID = id;
        account = ref;
        refresh();
    }

    public Analytics(Database db) {
        this.db = db;

    }

    public Analytics(Database db, long analyticsID, long parentID, String name) {
        this(db);
        this.analyticsID = analyticsID;
        this.parentID = parentID;
        this.name = name;
    }

    public void refresh() {
        Cursor cr = db.getReadableDatabase().rawQuery("SELECT "
                // 0   1     2          3
                + "id, name, id_parent, remark "
                + "FROM analytics "
                + "WHERE id = ?;",
                new String[]{"" + analyticsID});
        if (cr.moveToFirst()) {
            analyticsID = cr.getLong(0);
            name = cr.getString(1);
            parentID = cr.getLong(2);
            remark = cr.getString(3);
        }
        cr.close();

        refreshBalance();

        List<Analytics> tmp = new ArrayList<Analytics>(0);
        cr = db.getReadableDatabase().rawQuery("SELECT id "
                + "FROM analytics "
                + "WHERE id_parent = ? "
                + "ORDER BY name",
                new String[]{"" + analyticsID});
        if (cr.moveToFirst()) {
            do {
                tmp.add(new Analytics(db, account, cr.getLong(0)));
            } while (cr.moveToNext());
        }
        cr.close();
        values = tmp.toArray(new Analytics[]{});
    }

    public void append() {
        db.getWritableDatabase().execSQL("INSERT INTO analytics "
                + "(name, id_parent, remark) "
                + "VALUES (?,?,?);",
                new Object[]{name, parentID, remark});
        analyticsID = db.getIdent("analytics");
        DropboxThread.dataChanged();
    }

    public void update() {
        db.getWritableDatabase().execSQL("UPDATE analytics SET "
                + "name=?, id_parent=?, remark=? "
                + "WHERE id=?;",
                new Object[]{name, parentID, remark, analyticsID});
        DropboxThread.dataChanged();
    }

    public void delete() {
        db.getWritableDatabase().execSQL("DELETE FROM relates "
                + "WHERE id_analytics = ? "
                + "OR id_analytics IN ("
                + "   SELECT id "
                + "   FROM analytics "
                + "   WHERE id_parent = ?)",
                new Object[]{analyticsID, analyticsID});
        db.getWritableDatabase().execSQL("DELETE FROM links "
                + "WHERE id_analytics = ? "
                + "OR id_analytics IN ("
                + "   SELECT id "
                + "   FROM analytics "
                + "   WHERE id_parent = ?)",
                new Object[]{analyticsID, analyticsID});
        db.getWritableDatabase().execSQL("DELETE FROM analytics "
                + "WHERE id_parent = ?",
                new Object[]{analyticsID});
        db.getWritableDatabase().execSQL("DELETE FROM analytics "
                + "WHERE id = ?",
                new Object[]{analyticsID});
        DropboxThread.dataChanged();
    }

    public void refreshBalance() {
        double out = 0;
        double in = 0;

        if (account == null) {
            return;
        }

        balance = 0.0;
        balanceDebt = 0.0;
        balanceCredit = 0.0;

        if (parentID == -1) {

            Cursor cr = db.getReadableDatabase().rawQuery("SELECT "
                    + "SUM(amount) "
                    + "FROM balance, links, analytics "
                    + "WHERE id_from = ? "
                    + "AND balance.id = links.id_balance "
                    + "AND analytics.id = links.id_analytics "
                    + "AND analytics.id_parent = ?;",
                    new String[]{"" + account.accountID, "" + analyticsID});
            if (cr.moveToFirst()) {
                out = cr.getDouble(0);
            }
            cr.close();
            cr = db.getReadableDatabase().rawQuery("SELECT "
                    + "SUM(amount) "
                    + "FROM balance, links, analytics "
                    + "WHERE id_to=? "
                    + "AND balance.id = links.id_balance "
                    + "AND analytics.id = links.id_analytics "
                    + "AND analytics.id_parent = ?;",
                    new String[]{"" + account.accountID, "" + analyticsID});
            if (cr.moveToFirst()) {
                in = cr.getDouble(0);
            }
            cr.close();

        } else {

            Cursor cr = db.getReadableDatabase().rawQuery("SELECT "
                    + "SUM(amount) "
                    + "FROM balance, links "
                    + "WHERE id_from=? "
                    + "AND balance.id = links.id_balance "
                    + "AND links.id_analytics = ?;",
                    new String[]{"" + account.accountID, "" + analyticsID});
            if (cr.moveToFirst()) {
                out = cr.getDouble(0);
            }
            cr.close();
            cr = db.getReadableDatabase().rawQuery("SELECT "
                    + "SUM(amount) "
                    + "FROM balance, links "
                    + "WHERE id_to=? "
                    + "AND balance.id = links.id_balance "
                    + "AND links.id_analytics = ?;",
                    new String[]{"" + account.accountID, "" + analyticsID});
            if (cr.moveToFirst()) {
                in = cr.getDouble(0);
            }
            cr.close();
        }

        switch (account.type) {
            case Account.TYPE_NORMAL:
                balance = in - out;
                if (balance >= 0) {
                    balanceDebt = balance;
                    balanceCredit = 0.0;
                } else {
                    balanceCredit = -balance;
                    balanceDebt = 0.0;
                }
                break;

            case Account.TYPE_DEBT:
                balance = out - in;
                if (balance >= 0) {
                    balanceCredit = balance;
                    balanceDebt = 0.0;
                } else {
                    balanceDebt = -balance;
                    balanceCredit = 0.0;
                }
                break;

            case Account.TYPE_CARD:
                balance = in - out;
                if (in >= out) {
                    balanceDebt = in - out;
                    balanceCredit = 0.0;
                } else {
                    balanceCredit = out - in;
                    balanceDebt = 0.0;
                }

                break;
        }
    }

    /*
    public boolean linked() {
        return linked(account);
    }

    public boolean linked(Account account) {
        if (account == null) {
            return false;
        }

        Cursor cr = db.getReadableDatabase().rawQuery("SELECT COUNT(*) "
                + "FROM relates "
                + "WHERE id_account = ? "
                + "AND id_analytics = ?",
                new String[]{"" + account.accountID, "" + analyticsID});
        if (cr.moveToFirst() && cr.getInt(0) > 0) {
            return true;
        }
        return false;
    }

    public void link() {
        link(account);
    }

    public void link(Account account) {
        if (account == null) {
            return;
        }
        if (!linked(account)) {
            db.getWritableDatabase().execSQL("INSERT INTO "
                    + "relates (id_account, id_analytics) "
                    + "VALUES (?,?)",
                    new Object[]{account.accountID, analyticsID});
        }
    }

    public void unlink() {
        unlink(account);
    }

    public void unlink(Account account) {
        if (account == null) {
            return;
        }
        db.getWritableDatabase().execSQL("DELETE FROM relates "
                + "WHERE id_account = ? "
                + "AND id_analytics = ?",
                new Object[]{account.accountID, analyticsID});
    }
    */

    public int getValueIndex(Analytics an) {
        if (an == null) {
            return -1;
        }
        for (int i = 0; i < values.length; ++i) {
            if (values[i] != null && an.analyticsID == values[i].analyticsID) {
                return i;
            }
        }
        return -1;
    }

    public Analytics getValue(long id) {
        if (id < 0) {
            return null;
        }
        for (Analytics an : values) {
            if (an != null && an.analyticsID == id) {
                return an;
            }
        }
        return null;
    }

    public Analytics getValueByIndex(int id) {
        if (id < 0) {
            return null;
        }
        return values[id];
    }


    @Override
    public String toString() {
        return name;
    }

}
